package com.huan.vertxle.dao;

import com.huan.vertxle.initialization.PgSqlInit;
import com.huan.vertxle.model.ScanCode;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Slf4JLoggerFactory;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.RowSet;
import io.vertx.sqlclient.Tuple;

import java.util.Objects;

/**
 * @author huan
 */
public class ScanCodeDao {

  private final InternalLogger logger = Slf4JLoggerFactory.getInstance(this.getClass());

  private static ScanCodeDao scanCodeDao;

  private ScanCodeDao() {
  }

  public static ScanCodeDao getInstance() {
    if (Objects.isNull(scanCodeDao)) {
      scanCodeDao = new ScanCodeDao();
    }
    return scanCodeDao;
  }

  public Future<RowSet<Row>> enterWarehouse(ScanCode scanCode) {
    Promise<RowSet<Row>> promise = Promise.promise();
    PgSqlInit.client.preparedQuery("insert into  scan_code (code, weight, date, work_console) values ($1,$2,$3,$4);")
        .execute(Tuple.of(scanCode.getCode(), scanCode.getWeight(), scanCode.getDate(), scanCode.getWorkConsole()))
        .compose(rows -> this.getLast()).onSuccess(event -> {
          String code = event.iterator().next().getString("code");
          if (scanCode.getCode().equals(code)) {
            promise.complete(event);
          } else {
            logger.error("存储数据不一致:code->{}", code);
          }
        }).onFailure(promise::fail);
    return promise.future();
  }

  private Future<RowSet<Row>> getLast() {
    Promise<RowSet<Row>> promise = Promise.promise();
    PgSqlInit.client.query("select * from scan_code where id = (select max(id) from scan_code)").execute()
        .onSuccess(promise::complete).onFailure(promise::fail);
    return promise.future();
  }
}
